<template>
  <div class="content-wrap content-container" v-loading="loading">
    <!-- 搜索区域 -->
    <el-form class="search-wrap" v-model="searchFormData">
      <el-form-item class="search-wrap-item" label="标题关键字：" prop="projectTitle">
        <el-input min-width="160px" placeholder="请输入标题关键字" v-model="searchFormData.projectTitle" clearable
          @input="getAllRequirements"></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="时间：" prop="time">
        <el-date-picker style="width: 240px" type="daterange" unlink-panels range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间" :value-on-clear="null" v-model="searchFormData.time" @change="getAllRequirements" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="createRequirementClick">创建需求</el-button>
      </el-form-item>
    </el-form>

    <!-- [我负责的任务]列表区域 -->
    <div class="card-layout-box">
      <div class="card-not-requirement" v-if="allRequirements.length === 0">暂无数据</div>
      <!-- 分类 -->
      <div v-if="allRequirements.length !== 0" class="card-box" v-for="(list, index) in allRequirements"
        :key="index">
        <div class="card-header-box" :style="{ backgroundColor: fatherStatus(list.status)?.bgColor }">
          {{ fatherStatus(list.status).text }}:{{ list.total }}
        </div>
        <!-- 需求列表 -->
        <div class="card-list-box">
          <ul class="card-list">
            <li class="card-list-item" v-for="item in list.requirements" :key="item.fatherId" @click="handleTestMsg(item.childId)">
              <!-- 需求标题 -->
              <div>
                <el-text class="w-150px mb-2 card-header-title" truncated tag="b" @click="handleRowClick(item.fatherId)">
                  {{ item.requirementName }}
                </el-text>
              </div>
              <!-- 任务附加信息 -->
              <div class="card-list-small">
                <div class="card-small">
                  <div class="card-list-small-item boss-name" v-if="item.requirementAuditName">审核人：{{ item.requirementAuditName }}</div>
                  <div class="card-list-small-item boss-name"  v-if="item.requirementBossName">技术负责人：{{ item.requirementBossName == "" ? "无" :
                    item.requirementBossName }}</div>
                  <!-- <div class="card-list-small-item test-list" v-if="item.requirementRelevances">参与人：{{ item.requirementRelevances }}</div> -->
                  <div class="card-list-small-item test-list" v-if="item.userName">归属人{{ item.userName }}</div>
                  <!-- 测试中状态 -->
                  <div class="card-list-small-item test-list" :style="{ color: testStatus(item.submitTestNext)?.bgColor }" v-if="item.requirmentChildStatus == 5">{{ testStatus(item.submitTestNext)?.text }}</div>
                  <div class="card-list-small-item begin-time">创建日期：{{ tableTimeDate(item.beginTime) }}</div>
                </div>
                <!-- 研发人员操作 -->
                <div class="operate-box" v-if="item.requirmentChildStatus !== 9 && !isTestId">
                  <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                    <span class="el-dropdown-link">
                      <el-icon class="el-icon--right" color="#409EFF"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <!-- 提测需求前要先上传详细设计 -->
                        <el-dropdown-item v-if="item.requirmentChildStatus == 3" :command="{requirement:item, operate:fatherStatus(item.requirmentChildStatus).status}">
                          {{ item.itemRequirementWorldDetailed == "" ? "上传详细设计" : item.isGetTest == 1 ? '评分' : fatherStatus(item.requirmentChildStatus).operate  }}
                        </el-dropdown-item>

                        <!-- 已上传详细设计，未提测 -->
                        <el-dropdown-item v-if="item.requirmentChildStatus !== 9 && item.requirmentChildStatus < 4 && item.requirmentChildStatus !== 3" :command="{requirement:item, operate: fatherStatus(item.requirmentChildStatus).status}">
                          {{ fatherStatus(item.requirmentChildStatus).operate  }}
                        </el-dropdown-item>
                        
                        <!-- 重新提测 -->
                        <el-dropdown-item v-if="!isTestId && item.requirmentChildStatus == 5" :command="{requirement: item, operate:fatherStatus(item.requirmentChildStatus).status}">
                          重新提测
                        </el-dropdown-item>

                        <el-dropdown-item :command="{requirement:item, operate: 9}">关闭</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>

                <!-- 测试人员操作 -->
                <div class="operate-box" v-if="item.requirmentChildStatus !== 9 && isTestId && item.requirmentChildStatus > 4">
                  <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                    <span class="el-dropdown-link">
                      <el-icon class="el-icon--right" color="#409EFF"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-if="item.requirmentChildStatus == 5"
                          :command="{requirement:item, operate: fatherStatus(item.requirmentChildStatus).status}"
                        >
                          {{ fatherStatus(item.requirmentChildStatus).operate  }}
                        </el-dropdown-item>
                        <el-dropdown-item :command="{requirement:item, operate: 9}">关闭</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 待开发->开发中：需求评审会议纪要 -->
    <el-dialog  
      style="min-height: 540px;" 
       :close-on-click-modal="false"
      v-model="dialogReviewMeetVisible" 
      title="状态变更"
      @close="handleCloseDiglog"
      @closed="handleCloseDiglog">
      <el-form>
        <el-form-item label="需求评审会议纪要：">
          <el-input
            style="max-height: 500px; overflow-y: auto;"
            :autosize="{ minRows: 20, maxRows: 20 }"
            placeholder="请输入会议纪要..."
            type="textarea"
            v-model="reviewMeetingMsg"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleCloseDiglog">取消</el-button>
          <el-button type="primary" @click="handleDeveloping">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 开发中->提测中：上传详细设计，提测分支 -->
    <!-- 提测前上传详细设计 -->
    <el-dialog
    class="dialog-container"
      style="
        min-height: 400px;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
      "
       :close-on-click-modal="false"
      v-model="dialogDesignFileVisible"
      title="请上传详细设计"
      @close="handleCloseDiglog"
      @closed="handleCloseDiglog"
    >
      <el-upload
        class="upload-demo"
        drag
        action=""
        :multiple="false"
        :limit="1"
        v-model:file-list="designFileText"
        :http-request="handleUpLoad"
        :on-error="handleError"
        :on-remove = "handleRemove"
        :on-exceed = "handleExceed"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleCloseDiglog">取消</el-button>
          <el-button type="primary" @click="handleDesignFile(isRequirementData.childId)">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 提交提测分支 -->
    <el-dialog
      class="dialog-container"
      style="
        min-height: 600px;
        display: flex;
        flex-direction: column;
      "
      :close-on-click-modal="false"
      v-model="dialogTestVisible"
      title="操作"
      @close="handleCloseTestDialog"
      @closed="handleCloseTestDialog"
    >
      <el-form
        class="dialog-test-form"
        label-position="right"
        label-width="150px"
        ref="testFormRef"
        :rules="testFormRules"
        :model="testFormData"
      >
        <el-form-item v-if="isRequirementData.isGetTest == 2" label="是否涉及代码改动：">
          <el-switch
          v-model="isChangeData"
          inline-prompt
          active-text="是"
          inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="选择测试：" v-if="isRequirementData.isGetTest == 2" prop="ts">
          <el-select
            v-model="testFormData.ts"
            multiple
            :placeholder="testOptions.length == 0 ? '暂未分配，请通知测试负责人分配测试人员' : '请选择测试人员'"
            :required="isChangeData"
          >
          <el-option
            v-for="item in testOptions"
            :key="item.uuid"
            :label="item.nickName"
            :value="item.uuid"
          />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isRequirementData.isGetTest == 2" label="提测产品分支：" :required="isChangeData" prop="pullBranch1">
          <el-input v-model="testFormData.pullBranch1" placeholder="请输入产品分支"></el-input>
        </el-form-item>
        <el-form-item v-if="isRequirementData.isGetTest == 2" label="提测项目分支：" :required="isChangeData" prop="pullBranch2">
          <el-input v-model="testFormData.pullBranch2" placeholder="请输入项目分支"></el-input>
        </el-form-item>
        <el-form-item v-if="isRequirementData.isGetTest == 2" label="提测内容说明：" required prop="submitTest">
          <el-input 
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"  
            v-model="testFormData.submitTest" 
            placeholder="请简述提测内容...">
          </el-input>
        </el-form-item>
        <el-form-item label="对研发负责人评论：" required prop="itemRequirementYTOYTip">
          <el-input 
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"  
            v-model="testFormData.itemRequirementYTOYTip" 
            placeholder="请写下对研发负责人的评语">
          </el-input>
        </el-form-item>
        <el-form-item label="对研发负责人评分：" required prop="itemRequirementYTOYNumber">
          <el-input-number v-model="testFormData.itemRequirementYTOYNumber" controls-position="right" min="0" />
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer">
            <el-button type="defalut" @click="handleCloseTestDialog">取消</el-button>
            <el-button type="primary" @click="submitTestData(testFormRef)">确定</el-button>
          </div>
        </el-form-item>

      </el-form>
    </el-dialog>

    <!-- 测试不通过-重新提测 -->
    <el-dialog
      v-model="dialogAgainTestVisible"
      title="重新提测"
      :close-on-click-modal="false"
      @close="handleCloseTestDialog"
      @closed="handleCloseTestDialog"
    >
      <el-form
        label-position="right"
        label-width="120px"
        ref="againTestFormRef"
        :rules="againTestFormRules"
        :model="againTestFormData"
      >
        <el-form-item label="选择测试：" prop="childChildId">
          <el-select
             style="width: 240px"
            v-model="againTestFormData.childChildId"
            filterable
            clearable
            placeholder="请选择测试人员"
          >
          <el-option
            v-for="item in againTestOptions"
            :key="item.ID"
            :label="item.testName"
            :value="item.ID"
            :disabled="item.testStatus < 5"
          />
          </el-select>
        </el-form-item>
        <el-form-item label="提测产品分支：" prop="pullBranch1">
          <el-input v-model="againTestFormData.pullBranch1" placeholder="请输入产品分支"></el-input>
        </el-form-item>
        <el-form-item label="提测项目分支：" prop="pullBranch2">
          <el-input v-model="againTestFormData.pullBranch2" placeholder="请输入项目分支"></el-input>
        </el-form-item>
        <el-form-item label="提测内容说明：" prop="submitTest">
          <el-input 
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"  
            v-model="againTestFormData.submitTest" 
            placeholder="请简述提测内容...">
          </el-input>
        </el-form-item>
        <el-form-item>
          <div class="dialog-form-footer">
            <el-button type="primary" @click="handleCloseAgainTestDialog">取消</el-button>
            <el-button type="primary" @click="submitAgainTestData(againTestFormRef)">确定</el-button>
          </div>
        </el-form-item>

      </el-form>
    </el-dialog>

     <!-- 测试中操作弹窗 -->
     <el-dialog v-model="dialogTestResultVisible" title="测试结果" :close-on-click-modal="false" @close="handleCloseTestScoresDialog" @closed="handleCloseTestScoresDialog">
      <div v-if="isRequirementData.isGetTest == 1">
        <el-form>
          <el-form-item style="width: 100%;">
            <p style="text-align: center;"><span style="font-weight: bold;">{{ isRequirementData.requirementName }}</span>，确认通过吗？</p>
          </el-form-item>
          <el-form-item>
            <div>
              <el-button @click="handleCloseTestScoresDialog">取消</el-button>
              <el-button type="primary" @click="handleUpdateSubmitNotTip">通过</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div v-if="isRequirementData.isGetTest == 2">
        <div>
          <span>测试是否通过：</span>
          <el-switch
            v-model="isTestResult"
            inline-prompt
            active-text=" 通过 "
            inactive-text="不通过"
            :size="'large'"
            @change="handleChangeIsTestResult"
          />
        </div>
        <!-- 测试通过表单 -->
        <el-form
          label-position="left"
          label-width="120px"
          v-if="isTestResult" 
          ref="showTipCTOYRef" 
          :rules="showTipCTOYRules" 
          :model="showTipCTOYForm"
        >
          <el-form-item label="请选择提测人：" prop="childChildIdId" label-width="120px">
            <el-select v-model="showTipCTOYForm.childChildIdId" placeholder="请选择提测人" style="width: 240px" clearable filterable>
              <el-option
                v-for="item in allTestUserList"
                :key="item.ID"
                :label="item.submitTestName"
                :value="item.ID"
                :disabled="item.testStatus == 4 || item.testStatus == 1 || item.testStatus == 5"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="对研发评论：" prop="itemRequirementCTOYTip" label-width="120px">
              <el-input 
                :autosize="{ minRows: 4, maxRows: 8 }"
                type="textarea"  
                v-model="showTipCTOYForm.itemRequirementCTOYTip" 
                placeholder="请写下对研发的评语">
              </el-input>
          </el-form-item>
          <el-form-item label="对研发评分：" prop="itemRequirementCTOYNumber" label-width="120px">
            <el-input-number v-model="showTipCTOYForm.itemRequirementCTOYNumber" controls-position="right" min="0" />
          </el-form-item>
          <el-form-item>
              <div class="dialog-form-footer">
                <el-button @click="handleCloseTestScoresDialog">取消</el-button>
                <el-button type="primary" @click="submitScoreData(showTipCTOYRef)">通过</el-button>
              </div>
          </el-form-item>
        </el-form>
  
        <!-- 测试不通过表单 -->
        <el-form 
          label-position="left"
          label-width="140px"
          v-if="!isTestResult" 
          ref="testFaliedBugRef" 
          :rules="testFaliedBugRules" 
          :model="testFaliedBugForm"
        >
          <el-form-item label="请选择提测人：" prop="childChildId" label-width="120px">
            <el-select 
              v-model="testFaliedBugForm.childChildId" 
              placeholder="请选择提测人" 
              style="width: 240px" 
              clearable 
              filterable>
              <el-option
                v-for="item in allTestUserList"
                :key="item.ID"
                :label="item.submitTestName"
                :value="item.ID"
                :disabled="item.testStatus == 4 || item.testStatus == 1 || item.testStatus == 5"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择测试Bug：" prop="bugIds" label-width="120px">
            <p v-if="allBugList.length == 0">暂无Bug，请<span style="color: #409EFF;cursor: pointer;" @click="handleAddBugRouter">先添加Bug</span></p>

            <!-- bug列表不为空 -->
            <el-transfer
              v-if="allBugList.length !== 0"
              v-model="testFaliedBugForm.bugIds"
              :data="allBugList"
              filterable
              filter-placeholder="搜索"
              :titles="['未选中', '已选中']"
            />
          </el-form-item>
          <el-form-item>
            <div class="dialog-form-footer">
              <el-button @click="handleCloseTestScoresDialog">取消</el-button>
              <el-button type="primary" @click="handleTestFalied(testFaliedBugRef)">不通过</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 查看需求详情弹窗 -->
    <el-dialog v-if="dialogInfoVisible" style="width: 1200px;" :close-on-click-modal="false" v-model="dialogInfoVisible" @close="handleCloseDiglog" @closed="handleCloseDiglog">
        <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData"></CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { ElForm } from "element-plus";
import { 
  getNewFatherRequirementStatus, 
  postPVPRequirement, 
  PutShowNeedTip, 
  PostSubmitTestStatus,
  GetJoinTests,
  postSubmitTestRequirement,
  GetUpdateSubmitNotTips,
  PutShowTipCTOY,
  GetRequirementsBugs,
  GetSubmitRequirementList,
  GetMySubmitByRequirementChild,
  PostSubmitTestRequirementTwo,
  GetSubmitTestMsg,
} from "@/api/newDemands/index";
import { postRequirementCase } from "@/api/project/index";
import { postUploadFile } from "@/api/common/index";
import { handleUploadRequirement } from "@/utils/common";
import { tableTimeDate, fatherStatus, isUserAuthId, isValidateString, testStatus} from "@/utils/utils";
import useCommonDataStore from "@/store/common/common";
import CommonRequirementInfoVue from "../comomRequirementInfo.vue";

let router = useRouter();
let useCommonStore = useCommonDataStore();
const loading = ref(false);
const userAuthId = ref<any>(null);//当前用户权限id
const isTestId = ref<any>(null);//是否为测试人员
const allRequirements = ref<any>([]); // 我所有的研发任务
const searchFormData = ref({
  projectTitle: "",
  time: [null, null]
});

const dialogInfoVisible = ref(false);//查看需求弹窗控件
const clearData = ref(false);//控制是否清空子组件数据
const dialogDesignFileVisible = ref(false);//控制上传详细设计弹窗控件
const dialogTestVisible = ref(false);//控制提测弹窗控件
const dialogReviewMeetVisible = ref(false);//控制需求评审会议纪要弹窗
const dialogUploadCasesVisible = ref(false);//控制上传测试弹窗控件
const isChangeData = ref(true);//控制是否涉及代码改动滑块
const isUploadCases = ref(true);//控制是否上传测试用例滑块
const dialogTestResultVisible = ref(false);//控制测试是否通过弹窗控件
const dialogAgainTestVisible = ref(false);//控制重新提测弹窗控件


const isRequirementID = ref(); //当前操作任务ID
const isRequirementData = ref<any>(null);//当前需求数据
const designFileText = ref([]);//概要设计文件显示
const designFilePath = ref("");//概要设计文件地址
const reviewMeetingMsg = ref("");//需求评审会议纪要内容
const testFormRef = ref<FormInstance>();//提测表单实例
const testOptions = ref<any>([]);//提测测试人员列表
// const checkTests = ref<any>([]);//选中提测测试
// const testScoreRef = ref<FormInstance>();//测试对研发评论表单实例

const testFormData = ref<any>({
  childId: null,
  ts: [],
  pullBranch1: "",
  pullBranch2: "",
  submitTest: "",
  itemRequirementYTOYTip: "",
  itemRequirementYTOYNumber: null
  
});//提测数据
// const caseFormData = ref<any>();// 导入测试用例数据
// const testScoreData = ref<any>({
//   requirementChildId: null,
//   itemRequirementCTOYTip: "",
//   itemRequirementCTOYNumber: 100
// });// 测试对研发评论表单数据

// 自定义不能为空值的校验规则
const pullBranch1Validator = (rule: any, value: any, callback: any) => {
  if(isChangeData.value) {
    if(value.trim() == "") {
      return callback(new Error("必填，且不能为空"));
    };
  }
  callback();
};
const commonValidator = (rule: any, value: any, callback: any) => {
  if(value.trim() == "") {
    return callback(new Error("必填，且不能为空"));
  };
  callback();
};

const testFormRules = reactive<FormRules<any>>({
  ts: [
    { required: isChangeData.value, message: "必填", trigger: "blur"}
  ],
  pullBranch1: [ 
    { required: isChangeData.value, message: "必填", trigger: "blur" },
    { required: isChangeData.value, validator: pullBranch1Validator, trigger: "blur" }
  ],
  pullBranch2: [ 
    { required: true, message: "必填", trigger: "blur" },
    { required: isChangeData.value,validator: pullBranch1Validator, trigger: "blur"}
  ],
  submitTest: [ 
    { required: true, message: "必填", trigger: "blur" },
    { required: isChangeData.value,validator: pullBranch1Validator, trigger: "blur"}
  ],
  itemRequirementYTOYTip: [ 
    { required: true, message: "必填", trigger: "blur" },
    { validator: commonValidator, trigger: "blur"}
  ],
  itemRequirementYTOYNumber: [{ required: true, message: "必填", trigger: "blur" }],
});//提测数据校验规则


/* 测试中 */
// 研发参与的测试任务
const isTestResult = ref(true);// 控制测试是否通过;
//* 测试通过-对研发评论
const showTipCTOYRef = ref<FormInstance>();//测试通过表单实例
// 测试通过-对研发评论的表单校验规则
const showTipCTOYRules = reactive({
  childChildIdId: [{ required: true, message: "必填", trigger: "blur", }],
  itemRequirementCTOYTip: [
    { 
      required: true,
      message: "必填", 
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (isValidateString(value)) {
          callback(new Error("必填，且不能为空格或空行！"));
        } else {
          callback();
        }
      }
    },
  ],
  itemRequirementCTOYNumber: [{ required: true, message: "必填", trigger: "blur", }],
});
// 测试通过-对研发评论表单数据
const showTipCTOYForm = ref<any>({
    childChildIdId: null,
    itemRequirementCTOYTip: "",
    itemRequirementCTOYNumber: 100
});

//* 测试不通过-提交bug列表
const allBugList = ref<any>([]);// 根据需求id获取到的所有bug
const allTestUserList = ref<any>([]);// 根据需求id获取给自己提测的研发人员名单
const testFaliedBugRef = ref<FormInstance>();// 测试不通过时的表单实例
// 测试通过-对研发评论的表单校验规则
const testFaliedBugRules = reactive({
  childChildId: [{ required: true, message: "必填", trigger: "blur", }],
  bugIds: [{
    required: true,
    message: "必选", 
    trigger: "blur", 
    validator: (rule: any, value: any, callback: any) => {
        // 调用自定义验证函数
        if (value.length == 0) {
          callback(new Error("请添加提测bug!"));
        } else {
          callback();
        }
      }
  }],
});
const testFaliedBugForm = ref<any>({
  childChildId: null,
  bugIds: []
});

// * 测试不通过-研发重新提测
const againTestOptions = ref<any>([]);// 重新提测的测试人员列表
const againTestFormRef = ref<FormInstance>();// 重新提测表单实例
const againTestFormRules = reactive({
  childChildId:[
    { required: true, message: "必填", trigger: "blur" },
  ],
  pullBranch1: [ 
    { required: true, message: "必填", trigger: "blur" },
    { required: true, validator: pullBranch1Validator, trigger: "blur" }
  ],
  pullBranch2: [ 
    { required: true, message: "必填", trigger: "blur" },
    { required: true,validator: pullBranch1Validator, trigger: "blur"}
  ],
  submitTest: [ 
    { required: true, message: "必填", trigger: "blur" },
    { validator: pullBranch1Validator, trigger: "blur"}
  ],
});// 重新提测表单校验规则
const againTestFormData = ref<any>({
  childChildId: null,
  pullBranch1: "",
  pullBranch2: "",
  submitTest: ""
});// 重新提测表单数据





// TODO 点击创建任务
const createRequirementClick = () => {
  router.push({
    path: "/requirement/create",
  });
};

// TODO 点击跳转到Bug页面
const handleAddBugRouter = () => {
  router.push({
    path: "/experiment/bugs",
  });
};



// TODO 获取我所有的研发任务、分类并计数
const getAllRequirements = async () => {
  loading.value = true;
  userAuthId.value = localStorage.getItem("authorityId");
  isTestId.value = isUserAuthId(userAuthId.value);

  const { data } = await postPVPRequirement({
    projectTitle: searchFormData.value.projectTitle,
    beginTime: searchFormData.value.time === null ? null : searchFormData.value.time[0],
    endTime: searchFormData.value.time === null ? null : searchFormData.value.time[1]
  });

  if (data.code === 200) {
    if (data.data === null) {
      allRequirements.value = [];
      loading.value = false;
      return;
    } else {
      allRequirements.value = data.data;

      if (allRequirements.value.length > 0) {
        // 1、将响应数据根据requirementFatherStatus进行分类并统计
        const statusCount = {} as any;

        allRequirements.value.forEach((item: any) => {
          let childStatus = item.requirmentChildStatus;

          if (statusCount[childStatus]) {
            statusCount[childStatus].total++;
            // 判断该item是否已经添加
            if (!statusCount[childStatus].requirements.includes(item.ID)) {
              statusCount[childStatus].requirements.push(item);
            }
          } else {
            statusCount[childStatus] = {
              status: Number(childStatus),
              total: 1,
              requirements: [item]
            }
          }
        });

        allRequirements.value = Object.values(statusCount);
      }

      console.log("我的所有研发任务：",allRequirements.value)
    }
  } else {
    ElMessage.error(data.msg);
    return;
  };

  loading.value = false;
};

// 查看需求
const handleRowClick = async (id: number) => {
  console.log("查看需求:", id);
  dialogInfoVisible.value = true;
  isRequirementID.value = id;
};


// ! 操作
const handleCommand = async (val: any) => {
  console.log("当前需求：", val);
  console.log("当前操作：", val.operate);
  isRequirementID.value = val.requirement.fatherId;
  isRequirementData.value = val.requirement;

  switch (val.operate) {
    case 1:
      break;
    case 2:
      dialogReviewMeetVisible.value = true;
      break;
    case 3:
      // 根据itemRequirementWorldDetailed判断是否已经上传详细设计
      if(val.requirement.itemRequirementWorldDetailed == "") {
        // 若没有上传，则开启上传详细设计弹窗
        dialogDesignFileVisible.value = true;
      } else {
        // 若已上传，则先获取已分配的测试人员列表，并开启提测弹窗
        await handleGetJoinTests(isRequirementID.value);
        testFormData.value.childId = val.requirement.childId;
        if (isRequirementData.value.isGetTest == 1) {
          isChangeData.value = false;
        } else {
          isChangeData.value = true;
        }
        dialogTestVisible.value = true;
      }
      break;
    case 4:
     ElMessage.info("审核详细设计");
     break;
     case 5:
      console.log("是否为测试：", isTestId.value);
      //  测试操作
      if(isTestId.value) {
        // ElMessage.info("测试操作");
        //  如果研发参与了
        if (isRequirementData.value.isGetTest == 2) {
          await handleTestUserList(isRequirementID.value);
          console.log("提测人员列表：", allTestUserList.value)
          await handleAllBugList(isRequirementID.value);
        };
    
        dialogTestResultVisible.value = true;

    } else{
      //  研发操作
      // ElMessage.info("研发操作")
      await handleAgainTestList(isRequirementID.value);
      dialogAgainTestVisible.value = true;
    } 



     
       /* //  提测中——>测试中，开启【上传用例弹窗】
       designFileText.value = [];
       designFilePath.value = "";
       caseFormData.value = null;
       isUploadCases.value = true;
       dialogUploadCasesVisible.value = true;
       // await updateChildStatus(val.requirement, val.operate);

      // 开启测试对研发评分弹窗
      // dialogTestScoreVisible.value = true; */

      break;
    case 6:
      ElMessage.info("待上线");
      break;
    case 7:
      ElMessage.info("已上线");
      break;
    case 9:
      // 关闭childStatus，并刷新fatherStatus
      await updateChildStatus(isRequirementData.value , val.operate);
      break;
    default:
      // 关闭childStatus，并刷新fatherStatus
      await updateChildStatus(isRequirementData.value , val.operate);
      break;
  }
};

// TODO 待开发->开发中：需求评审会议纪要
const handleDeveloping = async () => {
  console.log("待开发->开发中：", isRequirementData.value);
  // 判断会议纪要是否为空
  if(reviewMeetingMsg.value.trim() == "") {
    ElMessage.warning("请填写需求评审会议纪要！");
    return;
  } else {
    // 提交会议纪要
    const { data } = await PutShowNeedTip({
      requirementChildId: isRequirementData.value.childId,
      itemRequirementNeedEasy: reviewMeetingMsg.value
    });
    if(data.code === 200) {
      ElMessage.success(data.msg);
      dialogReviewMeetVisible.value = false;
      loading.value = true;
      // 刷新fatherStatus
      await updateFatherStatus(isRequirementID.value);
      await getAllRequirements();
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    }
  }
};


// TODO 自定义上传文件
const handleUpLoad = async (options: any) => {
 const { data } = await postUploadFile(options.file, "detailedPath", "3");
 if(data.code === 200) {
  // 文件地址
  designFilePath.value = data.data.resultFilePath;
 } else {
  ElMessage.error(data.msg);
  throw console.error(data.msg);
 }
};

const handleError = (err: any) => {
  ElMessage.error(err);
};

const handleRemove = (file: any) => {
  console.log(file);
  designFileText.value = [];
  designFilePath.value = "";
};

const handleExceed = (exc: any) => {
  ElMessage.warning("只能上传1个文件！");
  return;
};

// 上传文件后将文件与需求绑定
const handleDesignFile = async (id: number) => {
  dialogDesignFileVisible.value = true;
  if(designFilePath.value == "") {
    ElMessage.warning("必须上传详细设计");
    return;
  } else {
    await handleUploadRequirement({
      itemRequirementId: id,
      fileType: 3,
      draftPath: null,
      summaryPath: null,
      detailedPath: designFilePath.value,
      meetingPath: null,
      onLineMeetingPath: null
    }).then(async() => {
      await handleGetJoinTests(isRequirementID.value);
      testFormData.value.childId = id;
      dialogTestVisible.value = true;
      dialogDesignFileVisible.value = false;
      
      loading.value = true;
      await getAllRequirements();
      loading.value = false;
    }).catch(() => {
      console.log("执行失败！");
      throw console.error();
    })
  }
};

// TODO 获取提测人员列表
const handleGetJoinTests = async (val: any) => {
  await GetJoinTests(val).then(async (res: any) => {
    console.log(res.data.data);
    if(res.data.data.length > 0) {
      testOptions.value = res.data.data;
      testFormData.value.ts = testOptions.value.map((item: any) => item.uuid);
    } else {
      testOptions.value.length = 0;
    }
  }).catch((error) => {
    throw console.error(error);
  });
};


// TODO 开发中->点击【提测】->提测中
const submitTestData = async (formEl: FormInstance | undefined) => {
  
  if(!formEl) {
    console.error("表单验证失败！");
    return;
  };
  
  const validatePromise = formEl.validate();
  // console.log("选中测试：", checkTests.value);
  console.log("表单测试：", testFormData.value.ts);
  try {
    await validatePromise;
    console.log("表单校验通过")
    
    //!! 处理提测测试
    // 如果不需要测试参与，直接提交分支和评论
    // if(isRequirementData.value.isGetTest == 1) {
      // 处理表单数据
      testFormData.value.ts = testOptions.value.filter((item: any) => testFormData.value.ts.includes(item.uuid)).map((item: any) => ({
        userName: item.nickName,
        uuid: item.uuid
      }));

      console.log(testFormData.value);


      // 提交提测表单数据,并更新状态
      const { data } = await postSubmitTestRequirement(testFormData.value);
      if(data.code === 200) {
        ElMessage.success(data.msg);
        dialogTestVisible.value = false;
        await updateChildStatus(isRequirementData.value, isRequirementData.value.requirmentChildStatus);
        console.log("提测通过后：", testFormData.value)
      } else {
        ElMessage.error(data.msg);
        throw console.error(data.msg);
      };

    /* } else if (isRequirementData.value.isGetTest == 2) {
      if(checkTests.value.length !== 0) {
        // checkTests.value = testOptions.value.map((item: any) => item.uuid);
  
        testFormData.value.ts = testOptions.value.filter((item: any) => checkTests.value.includes(item.uuid)).map((item: any) => ({
            userName: item.nickName,
            uuid: item.uuid
          }));
        
        console.log("提测",testFormData.value);
    
        // 提交提测表单数据,并更新状态
        const { data } = await postSubmitTestRequirement(testFormData.value);
        if(data.code === 200) {
          ElMessage.success(data.msg);
          dialogTestVisible.value = false;
          await updateChildStatus(isRequirementData.value, isRequirementData.value.requirmentChildStatus);
        } else {
          ElMessage.error(data.msg);
          throw console.error(data.msg);
        };
      } else if (isRequirementData.value.contactTestNames == "") {
        ElMessage.warning("请通知测试负责人分配测试！");
        return;
      } else {
        ElMessage.warning("请选择测试人员!");
        return;
      };
    }; */

    // else {
      // testFormData.value.ts = testOptions.value.filter((item: any) => checkTests.value.includes(item.uuid)).map((item: any) => ({
        //   userName: item.nickName,
        //   uuid: item.uuid
        // }));
        // console.log("处理后的数据：", testFormData.value);
        // };
        
  } catch (error) {
    // loading.value = false;
    ElMessage.error("表单校验失败");
    throw console.error(error);
  }
};

// TODO 更新childStatus，fatherStatus状态
const updateChildStatus = async (val: any, status: number) => {
  /* // if(status == 8) {
  //   await ElMessageBox.confirm("确认关闭该需求吗？","操作", {
  //     cancelButtonText:"取消",
  //     confirmButtonText: "确认",
  //   }).then (async ()=> {
  //     console.log("点击确认")
  //     // 更新需求状态
  //   const { data } = await putUpdateRequirementStatus({
  //     requirementId: val.childId,
  //     requirementStatusId: status
  //   });

  //   if (data.code !== 200) {
  //     ElMessage.warning(data.msg);
  //     return;
  //   } else {
  //     loading.value = true;
  //     // 刷新fatherStatus
  //     await updateFatherStatus(val.fatherId);
  //     await getAllRequirements();
  //     loading.value = false;
  // }
  //   })
  //   .catch(() => {
  //     console.log("取消关闭该需求！");
  //     return new Promise(() => { });
  //   });
  // } else {
  //   // 更新需求状态
  //   const { data } = await putUpdateRequirementStatus({
  //     requirementId: val.childId,
  //     requirementStatusId: status+1
  //   });
  
  //   if (data.code !== 200) {
  //     ElMessage.warning(data.msg);
  //     return;
  //   } else { */
      loading.value = true;
      // 刷新fatherStatus
      await updateFatherStatus(val.fatherId);
      await getAllRequirements();
      loading.value = false;
    // }
  // }
};

// TODO 关闭弹窗
const handleCloseDiglog = () => {
  console.log("关闭弹窗");
  // isRequirementData.value = null;

  // 清空会议评审纪要
  reviewMeetingMsg.value = "";
  dialogReviewMeetVisible.value = false;

  // 关闭上传详细设计弹窗
  designFileText.value = [];
  designFilePath.value = "";
  dialogDesignFileVisible.value = false;

  
  // 查看需求弹窗
  clearData.value = true;
};

// TODO 关闭提测分支弹窗
const handleCloseTestDialog = () => {
  // 关闭提测弹窗
  testFormData.value = {
    childId: null,
    ts: [],
    pullBranch1: "",
    pullBranch2: "",
    itemRequirementYTOYTip: "",
    itemRequirementYTOYNumber: null
  };
  dialogTestVisible.value = false;
};

// TODO 关闭上传测试弹窗
/* const handleCloseCaseDialog = () => {
  designFileText.value = [];
  caseFormData.value = null;
  dialogUploadCasesVisible.value = false;
}; */


//! TODO 上传并导入测试用例
const submitCaseData = async () => {
  if (isUploadCases.value == true) {
    if (designFileText.value.length > 0) {
      // ! 导入测试用例到需求中
      console.log("导入测试用例：", designFilePath.value);
      // 导入用例
      const { data } = await postRequirementCase({
        requirementId: isRequirementID.value,
        itemItemId: isRequirementData.value.itemItemId,
        filePath: designFilePath.value
      });
      console.log("导入结果：",data.code)
      // 导入用例成功则刷新用例表格
      if (data.code === 200) {
        ElMessage.success(data.msg);

        // 更新childStatus状态并刷新
        dialogUploadCasesVisible.value = false;
        loading.value = true;
        await updateChildStatus(isRequirementData.value, isRequirementData.value.requirmentChildStatus);
        await getAllRequirements();
        loading.value = false;
       
      } else {
        // 获取用例失败提示
        ElMessage.error(data.msg);
        throw Error(data.msg);
      }
    } else {
      ElMessage.warning("请先上传测试用例！");
      return;
    }
  } else {
    console.log("直接更改状态");
    await updateChildStatus(isRequirementData.value, isRequirementData.value.requirmentChildStatus);
    dialogUploadCasesVisible.value = false;
    loading.value = true;
    await getAllRequirements();
    loading.value = false;
  }
};

/* 测试中事件函数 */
// TODO 是否通过测试开关发生改变时触发事件
const handleChangeIsTestResult = async (val: number) => {
  if(val) {
    testFaliedBugForm.value = {
      childChildId: null,
      bugIds: []
    };
    testFaliedBugRef.value?.resetFields();
  } else {
    showTipCTOYForm.value = {
      childChildIdId: null,
      itemRequirementCTOYTip: "",
      itemRequirementCTOYNumber: 100
    };
    showTipCTOYRef.value?.resetFields();
  }
};

// TODO 关闭测试中操作弹窗
const handleCloseTestScoresDialog = () => {
  isTestResult.value = true;
  showTipCTOYForm.value = {
    childChildIdId: null,
    itemRequirementCTOYTip: "",
    itemRequirementCTOYNumber: 100
  };
  testFaliedBugForm.value = {
    childChildId: null,
    bugIds: []
  };
  testFaliedBugRef.value?.resetFields();
  showTipCTOYRef.value?.resetFields();
  dialogTestResultVisible.value = false;
  console.log("关闭", isRequirementData.value)
};

// TODO 测试通过不需要评价
const handleUpdateSubmitNotTip = async () => {
  const { data } = await GetUpdateSubmitNotTips(isRequirementData.value.childId);
  if(data.code === 200) {
    ElMessage.success(data.msg);
    handleCloseTestScoresDialog();
    loading.value = true;
    await getAllRequirements();
    loading.value = false;
  } else {
    ElMessage.error(data.msg);
    throw console.error(data.msg);
  };
};

// TODO 测试通过，并对研发评论
const submitScoreData = async (formEl: FormInstance | undefined) => {
  console.log(formEl)
  if(!formEl) {
    console.error("表单验证失败！");
    return;
  };

  const validatePromise = formEl.validate();
  try {
    await validatePromise;

    console.log("表单校验通过：", showTipCTOYForm.value);

    const { data } = await PutShowTipCTOY(showTipCTOYForm.value);
    if(data.code === 200) {
      ElMessage.success(data.msg);
      handleCloseTestScoresDialog();
      loading.value = true;
      await getAllRequirements();
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    }
  } catch (error) {
    loading.value = false;
    throw console.error(error);
  }
};

// TODO 测试获取所有提测人员列表
const handleTestUserList = async (id: number) => {
  const { data } = await GetMySubmitByRequirementChild(id);
  if (data.code === 200) {
    allTestUserList.value = data.data;
  } else {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 根据需求ID获取bug列表
const handleAllBugList = async (id: number) => {
  const { data } = await GetRequirementsBugs(id);
  console.log("所有bug列表：", data.data[0].requirementBugs);
  if (data.code == 200) {
    if (data.data[0].requirementBugs.length !== 0) {
      allBugList.value = data.data[0].requirementBugs.map((item: any) => {
        return {
          key: item.ID,
          label: item.bug_title,
          disabled: (item.bug_status == 6 || item.bug_status == 7) ? true : false,
        }
      });

    } else {
      allBugList.value = [];
    }
  } else {
    ElMessage.error(data.msg);
    return;
  }
};


// TODO 测试不通过
const handleTestFalied = async (formEl: FormInstance | undefined) => {
  console.log("测试不通过");
  if(!formEl) {
    console.error("表单验证失败！");
    return;
  };

  const validatePromise = formEl.validate();
  try {
    await validatePromise;
    console.log("表单验证成功！", testFaliedBugForm.value);

    const { data } = await PostSubmitTestStatus(testFaliedBugForm.value);
    if (data.code === 200) {
      ElMessage.success(data.msg);
      handleCloseTestScoresDialog();
      loading.value = true;
      await getAllRequirements();
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      return;
    }
  } catch (error) {
    console.log("表单验证失败！");
    throw console.error(error);
  }
};

// TODO 研发人员重新提测时获取测试名单
const handleAgainTestList = async (id: number) => {
  const { data } = await GetSubmitRequirementList(id);
  if (data.code === 200) {
    againTestOptions.value = data.data;
    console.log("测试人员列表：", againTestOptions.value);
  } else {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 关闭重新提测弹窗
const handleCloseAgainTestDialog = () => {
  againTestFormData.value = {
    childChildId: null,
    pullBranch1: "",
    pullBranch2: "",
    submitTest: ""
  };
  againTestFormRef.value?.resetFields();
  dialogAgainTestVisible.value = false;
};

// TODO 提交重新提测表单数据
const submitAgainTestData = async (formEl: FormInstance | undefined) => {
  if(!formEl) {
    console.error("表单验证失败！");
    return;
  };
  
  const validatePromise = formEl.validate();
  try {
    await validatePromise;

    const { data } = await PostSubmitTestRequirementTwo(againTestFormData.value);
    if(data.code === 200) {
      ElMessage.success(data.msg);
      handleCloseAgainTestDialog();
      loading.value = true;
      await getAllRequirements();
      loading.value = false;
      
    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    };
  } catch (error) {
    ElMessage.error("表单校验失败");
    throw console.error(error);
  }
};

// TODO 获取提测详情
const handleTestMsg = async (id: number) => {
  const {data} = await GetSubmitTestMsg(id);
  console.log("提测详情：", data);
}




// 刷新fatherStatus
const updateFatherStatus = async (id: number) => {
  const { data } = await getNewFatherRequirementStatus({
    requirementId: id
  });

  if (data.code !== 200) {
    ElMessage.error(data.msg);
    return;
  }
};

onMounted(async () => {
  await getAllRequirements();
  
});
</script>

<style lang="scss" scoped>
.content-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;

  // TODO 搜索区域
  .search-wrap {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #dcdfe6;

    .search-wrap-item {
      margin-right: 20px;
      min-width: 200px;
      font-weight: bold;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      color: #000;
    }
  };

  // 需求列表区域
  .card-layout-box {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;

    // 无数据时显示
    .card-not-requirement {
      color: #909399;
      margin: auto;
    }

    .card-box {
      // width: 100%;
      // width: 470px;
      width: 32%;
      height: 100%;
      height: 360px;
      border: 1px solid #909399;
      border-radius: 20px 20px 0 0;
      margin: 0 5px;
      display: flex;
      flex-direction: column;

      // margin: 0 10px 20px 0;
      // 列表标题
      .card-header-box {
        width: 100%;
        height: 40px;
        padding: 0 10px;
        line-height: 40px;
        font-size: 18px;
        font-family: Helvetica, Arial, sans-serif;
        color: white;
        border-radius: 20px 20px 0 0;
      }

      // 列表盒子
      .card-list-box {
        width: 100%;
        height: calc(100% - 40px);
        display: flex;
        justify-content: start;
        overflow-y: auto;

        .card-list {
          width: 100%;
          height: 100%;
          font-size: 14px;
          overflow-y: auto;

          .card-list-item {
            width: 100%;
            display: flex;
            flex-direction: column;
            border-bottom: 1px solid #ccc;
            cursor: pointer;
            padding: 5px 5px;
            overflow: hidden;
            position: relative;

            // 附加信息样式
            .card-list-small {
              width: 100%;
              display: flex;
              justify-content: space-between;
              flex-direction: row;
              padding: 0;
              font-size: 0.7rem;
              white-space: nowrap;
              
              .card-small {
                width: 455px;
                display: flex;
                justify-content: space-between;
                flex-direction: row;
              }

              .card-list-small-item {
                margin: 0 10px 0 0;
              }

              // .item-status {
              //   width: 120px;
              // }

              .boss-name {
                width: 100px;
              }

              .test-list {
                width: 180px;
                overflow: hidden;
                text-overflow: ellipsis;
              }

              .begin-time {
                width: 110px;
              }

              .operate-box {
                width: 20px;
                text-align: right;
              }
            }

            // 操作按钮样式
            .card-list-operate {
              justify-content: flex-end;
              width: 60px;
              position: absolute;
              right: 10px;
              top: 2px;
              opacity: 1;
              z-index: 999;

              .el-col {
                margin: 1px 0;
                text-align: right;
              }
            }
          }

          .card-list-item:hover {
            background-color: rgb(216.8, 235.6, 255);
          }

          .card-header-title:hover {
            color: #409EFF;
          }
        }
      }
    }
  };

  // 审核需求
  .record-title {
    display: flex;
    flex-direction: row;
    padding: 5px 10px;
    margin-bottom: 10px;
    background-color: #f0f0f0;
    border-radius: 2px;
    p {
      margin-right: 20px;
    }
  }

  // 需求草稿
  .info-file-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      flex-direction: row;
      margin: 10px 0 0;
      .info-content-title {
          width: 100px;
          padding: 0 10px;
      }

      .info-file-ul {
          width: calc(100% - 70px);
          text-align: left;
          display: flex;
          flex-direction: row;
          .info-file-item {
              width: 60px;
              margin-right: 10px;
          }
          .info-file-item:hover {
              color: #409EFF;
              cursor: pointer;
          }
      }
  }

  // TODO 分配需求弹窗
  .dialog-container {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .dialog-form-title {
      font-weight: bold;
      padding: 10px;
      margin-bottom: 20px;
      background-color: #f0f0f0;
    }

    .dialog-form-box {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: center;
      margin-bottom: 30px;

      .el-form-item {
        margin: 0 10px;
      }
    }

    .dialog-footer {
      width: 100%;
      text-align: right;
    }

    // 提测分支表单样式
    .dialog-test-form {
      max-height: 600px;
      overflow-y: auto;
      padding: 20px 20px 0 20px;
      
      .dialog-footer {
        text-align: right;
      }
    }

    // 上传测试用例样式
    .upload-case {
      margin-left: 20px;
    }
  }

  .dialog-form-footer {
    width: 100%;
    text-align: right;
  }
}
</style>
